package com.ithei.多线程第二天.牛奶模型;

public class Demo {
    public static void main(String[] args) {
        new Thread(() -> {
            //定义临时变量,计数(送奶的数量)
            int count = 0;
            while (true) {
                synchronized ("奶箱") {
                    if (Box.count == 0) {
                        System.out.println("================牛奶已经送完了================");
                        break;
                    } else {
                        if (Box.flag) {
                            try {
                                "奶箱".wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        } else {
                            count++;
                            System.out.println(Thread.currentThread().getName()+"在送第" + count + "瓶牛奶.........");
                            Box.flag = true;
                            "奶箱".notifyAll();
                        }
                    }
                }
            }
        },"送奶工人").start();
//Demo.class锁对象一致
        new Thread(() -> {
            //临时变量,计数
            int number = 0;
            while (true) {
                synchronized ("奶箱") {
                    if (Box.count == 0) {
                        System.out.println("================牛奶已经喝完了================");
                        break;
                    } else {
                        if (!Box.flag) {
                            try {
                                "奶箱".wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        } else {
                            number++;
                            System.out.println(Thread.currentThread().getName()+"正在喝第" + number + "瓶牛奶..........");
                            Box.count--;
                            Box.flag = false;
                            "奶箱".notifyAll();
                        }
                    }
                }
            }
        },"喝奶的少爷").start();
    }
}
